
package com.platform.modules.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.JedisUtil;
import com.platform.common.utils.Query;
import com.platform.modules.mall.dao.MallShopsDao;
import com.platform.modules.mall.entity.MallBrandEntity;
import com.platform.modules.mall.entity.MallShopsCategoryEntity;
import com.platform.modules.mall.entity.MallShopsEntity;
import com.platform.modules.mall.entity.dto.MallShopsDto;
import com.platform.modules.mall.location.utils.LocationUtil;
import com.platform.modules.mall.service.MallBrandService;
import com.platform.modules.mall.service.MallShopsCategoryService;
import com.platform.modules.mall.service.MallShopsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 店铺Service实现类
 *
 * @author
 * @date 2019-07-03 13:51:29
 */
@Service("mallShopsService")
public class MallShopsServiceImpl extends ServiceImpl<MallShopsDao, MallShopsEntity> implements MallShopsService {

    @Resource
    private MallBrandService brandService;
    @Resource
    private MallShopsCategoryService categoryService;
    @Autowired
    private JedisUtil jedisUtil;
    private static final String KEY="MallShopsServiceImpl_brand_list_";

    @Override
    public Map<String,Object> tradeAreaInfo(String id,String location) {
        location = location.replace(","," ");
        String shopsCount = String.format("(select count(1) from mall_shops where TRADE_AREA_ID = '%s' and `LEVEL` = 2 and IS_ON_SALE = 1 and DELETE_STATUS = 1) shopCount",id);
        String distance = String.format("FLOOR(ST_Distance( ST_GeomFromText ( 'point(%s)',4326), location))  distance",location);
        return this.getMap(new QueryWrapper<MallShopsEntity>().select("ID as id","NAME as name","IMG_URL as imageList",shopsCount,distance).eq("ID",id));
    }

    @Override
    public List<MallShopsEntity> queryAllByBrandId(String brandId) {
        StringBuilder sb =new StringBuilder(KEY).append(brandId);
        Object object = jedisUtil.getObject(sb.toString());
        if (object!=null){
            return (List<MallShopsEntity>) object;
        }
        List<MallShopsEntity> list = this.lambdaQuery().eq(MallShopsEntity::getBrandId, brandId).list();
        if (list!=null&&list.size()!=0){
            jedisUtil.setObject(sb.toString(),list);
        }
        return list;
    }

    @Override
    public MallShopsDto getShopBaseInfo(String id, String location) {
        location = location.replace(","," ");
        return this.getBaseMapper().shopsBaesInfo(id,location);
//        String distance = String.format("FLOOR(ST_Distance( ST_GeomFromText ( 'point(%s)',4326), location))  distance",location);
        // 查询基础信息
//        MallShopsEntity entity = this.getOne(new QueryWrapper<MallShopsEntity>()
//                .select("ID","name","SHOP_CATEGORY_ID","IMG_URL","SHOP_DESC","DETAILS","TELEPHONE",distance,"TRADE_AREA_ID","BRAND_ID","SHOP_SCORE","AVERAGE_PRICE","BUSINESS_PERMIT_IMG","ST_X(location) LATITUDE","ST_Y(location) LONGITUDE")
//                .eq("IS_ON_SALE",1)
//                .eq("DELETE_STATUS",1)
//                .eq("ID",id)
//        );
//        MallShopsDto dto = new MallShopsDto();
//        BeanUtils.copyProperties(entity,dto);
//        try {
//            dto.setShopCategoryName(categoryService.lambdaQuery().select(MallShopsCategoryEntity::getId,MallShopsCategoryEntity::getName).eq(MallShopsCategoryEntity::getId,dto.getShopCategoryId()).one().getName());
//            dto.setShopCategoryName(categoryService.lambdaQuery().select(MallShopsCategoryEntity::getId,MallShopsCategoryEntity::getName).eq(MallShopsCategoryEntity::getId,dto.getShopCategoryId()).one().getName());
//        }catch (Exception e){
//            e.printStackTrace();
//            log.error("获取店铺类型名称出错");
//        }
//        return dto;
    }

    @Override
    public List<MallShopsEntity> queryAll(Map<String, Object> params) {
        String name = (String) params.get("name");
        String userId = (String) params.get("userId");
        String level = (String) params.get("level");
        String type = (String) params.get("type");
        String orgNo = (String) params.get("orgNo");
        return baseMapper.selectList(new QueryWrapper<MallShopsEntity>()
                .like(StringUtils.isNotBlank(name), "NAME", name)
                .eq(StringUtils.isNotBlank(userId), "USER_ID", userId)
                .eq(StringUtils.isNotBlank(level), "level", level)
                .eq(StringUtils.isNotBlank(orgNo), "ORG_NO", orgNo)
                .eq(StringUtils.isNotBlank(type), "type", type));
    }

    @Override
    public IPage queryPage(Map<String, Object> params) {
        String name = (String) params.get("name");
        String type = (String) params.get("type");
        String userId = (String) params.get("userId");

        Page<MallShopsEntity> page = new Query<MallShopsEntity>(params).getPage();

        return baseMapper.selectPage(page,
                new QueryWrapper<MallShopsEntity>().like(StringUtils.isNotBlank(name), "NAME", name)
                        .eq(StringUtils.isNotBlank(userId), "USER_ID", userId)
                        .eq(StringUtils.isNotBlank(type), "TYPE", type)
                        .orderByDesc("SORT"));
    }

    @Override
    public boolean add(MallShopsEntity mallShops) {
        shopDataChange(mallShops,1);
        return this.save(mallShops);
    }

    @Override
    public boolean update(MallShopsEntity mallShops) {
        shopDataChange(mallShops,2);
        return this.updateById(mallShops);
    }

    /**
     * 店铺数据变化时调用
     * tag 1 add 2 update 3 delete
     */
    public void shopDataChange(MallShopsEntity shopsNew,int tag){

        if(tag <= 2){
            if(StringUtils.isNotBlank(shopsNew.getTradeAreaId())){
                // 设置区域信息
                MallShopsEntity area = this.getById(shopsNew.getTradeAreaId());
                if(area != null){
                    shopsNew.setDistrict(area.getDistrict());
                }
            }

            // 设置经纬度
            if(StringUtils.isNotBlank(shopsNew.getLocation())){
                shopsNew.setLocation("ST_GeomFromText('POINT(" + shopsNew.getLocation().replace(",","  ") + ")',4326)");
            }else{
                shopsNew.setLocation("ST_GeomFromText('POINT(0 0)',4326)");
            }

            // 设置 父分类 ID
            if(StringUtils.isNotBlank(shopsNew.getShopCategoryId())){
                shopsNew.setCategoryParentId(Optional.ofNullable(categoryService.getById(shopsNew.getShopCategoryId())).map(MallShopsCategoryEntity::getParentId).orElse(""));
            }
        }

        // 更新品牌下的店铺数量
        if(StringUtils.isNotBlank(shopsNew.getBrandId())){
            int count = 0;
            switch (tag){
                case 1:
                    count = 1;
                    break;
                case 2:
                    MallShopsEntity shopsOld = this.getById(shopsNew.getId());
                    if(!shopsOld.getBrandId().equals(shopsNew.getBrandId())){
                        brandService.lambdaUpdate().setSql("SHOP_COUNT = SHOP_COUNT - 1").eq(MallBrandEntity::getId,shopsOld.getBrandId()).update();
                        count = 1;
                    }
                    break;
                case 3:
                    count = -1;
                    break;
            }
            if(count != 0){
                brandService.lambdaUpdate().setSql("SHOP_COUNT = SHOP_COUNT + "+count).eq(MallBrandEntity::getId,shopsNew.getBrandId()).update();
            }
        }
    }

    @Override
    public boolean delete(String id) {
        shopDataChange(this.getById(id),3);
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        for (String id : ids){
            shopDataChange(this.getById(id),3);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public boolean myUpdate(MallShopsEntity mallShops, String userId) {
        MallShopsEntity entity = this.getById(mallShops.getId());
        if (!userId.equals(entity.getUserId())) {
            throw new BusinessException("非法操作！");
        }
        entity.setName(mallShops.getName());
        entity.setWorkTime(mallShops.getWorkTime());
        entity.setShopsSn(mallShops.getShopsSn());
        entity.setImgUrl(mallShops.getImgUrl());
//        entity.setLongitude(mallShops.getLongitude());
//        entity.setLatitude(mallShops.getLatitude());
        entity.setDetails(mallShops.getDetails());
        entity.setTelephone(mallShops.getTelephone());
        entity.setShopDesc(mallShops.getShopDesc());
        entity.setSort(mallShops.getSort());
        return update(entity);
    }

    @Override
    public IPage getNearbyShops(Map<String, Object> params) {
        //排序
        params.put("sidx", "distance");
        params.put("asc", true);
        Object range = params.get("range");
        try {
            // 注意 mysql8.0 以上 配合新的距离计算函数 此处需要换成 0，1  （纬度，经度）  旧版本使用 1，0 （经度，纬度）
            params.put("location", params.get("latitude") + " " + params.get("longitude"));
            if(range != null){
                params.put("scope", LocationUtil.getAroundLocations(Double.parseDouble(params.get("latitude").toString()), Double.parseDouble(params.get("longitude").toString()), 30,Float.parseFloat(range.toString())));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("获取当前位置出错！");
        }
        Page<MallShopsDto> page = new Query<MallShopsDto>(params).getPage();
        page.setRecords(baseMapper.getNearbyShopList(page, params));
        return page;
    }

    @Override
    public MallShopsDto getShopByIdForApp(String id) {
        return baseMapper.getShopByIdForApp(id);
    }

    @Override
    public IPage getNearbySimple(Map<String, Object> params) {
        LocationUtil.initialNearbyParams(params);
        //排序
        params.put("sidx", "distance");
        params.put("asc", true);
        Page<Map<String,Object>> page = new Query<Map<String,Object>>(params).getPage();
        page.setRecords(baseMapper.getNearbySimple(page, params));
        return page;
    }
}
